/**
 * Create by yxk at 2020/6/13
 */
import { jxcFieldQueryContactsByIdAPI } from '@/api/jxc/field'

export default {
  data() {
    return {
      receiveAddressForm: {
        discount: 0,
        contacts: '',
        telephone: '',
        detailAddress: ''
      },
      receiveAddressRules: {},
      receiveAddressFieldList: [
        { field: 'contacts', fieldName: 'contacts', name: '联系人', formType: 'text' },
        { field: 'telephone', fieldName: 'telephone', name: '电话', formType: 'mobile' },
        { field: 'detailAddress', fieldName: 'detailAddress', name: '地址', formType: 'text' }
      ]
    }
  },
  created() {
    this.generateAddressRules()
  },
  computed: {
    showReceiveAddress() {
      return this.type === 'jxc_sale'
    }
  },
  methods: {
    setDefaultReceiveAddress(data) {
      if (data.contactsId) {
        jxcFieldQueryContactsByIdAPI({
          contactsId: data.contactsId
        }).then(res => {
          const concatUser = res.data
          this.receiveAddressForm = {
            contacts: concatUser.name,
            telephone: concatUser.mobile,
            detailAddress: data.detailAddress
          }
        }).catch(() => {
          this.receiveAddressForm = {
            contacts: '',
            telephone: '',
            detailAddress: ''
          }
        })
      } else {
        this.receiveAddressForm = {
          contacts: data.contacts || '',
          telephone: data.mobile || data.telephone,
          detailAddress: data.detailAddress
        }
      }
    },

    generateAddressRules() {
      this.receiveAddressFieldList.forEach(field => {
        this.receiveAddressRules[field.field] = this.getRules(field)
      })
    },

    getReceiveAddress() {
      return new Promise((resolve, reject) => {
        const instance = this.$refs.receiveAddress.instance

        instance.validate(valid => {
          if (valid) {
            resolve(this.receiveAddressForm)
          } else {
            if (instance.fields) {
              for (
                let index = 0;
                index < instance.fields.length;
                index++
              ) {
                const ruleField = instance.fields[index]
                if (ruleField.validateState == 'error') {
                  this.$message.error(ruleField.validateMessage)
                  break
                }
              }
            }
            this.loading = false
            reject()
          }
        })
      })
    }
  }
}
